#Nature's Kidneys: the Role of Wetland Reserve Easements in Restoring Water Quality
#Nicole Karwowski and Marin Skidmore
#Replication File
#2025

#Extract population estimates from population raster


#load packages
#load libraries
library(ggplot2)
library(raster)
library(sf)
library(exactextractr)
library(Rcpp)
library(data.table)
library(tidyverse)
library(Hmisc)
library(haven)
library(stargazer)
library(purrr)
library(tidyr)
library(collapse)
library(ggthemes)
library(scales)
library(tigris)
options(tigris_use_cache = TRUE)
library(mapview)
options(scipen=999)
library(stringr)
library(data.table)
library(lubridate)
library(units)
library(geosphere)
library(plm)
library(lmtest)
library(sandwich)
library(fixest)
library(did)
library(stargazer)
library(naniar)
library(scales)
library(terra)
library(CropScapeR) 
library(rgeos)
library(sp)
library(reshape2)
library(mapview)
library(leaflet)
library(exactextractr)

#open raster
setwd("C:/Users/16308/OneDrive - Montana State University/UW_Madison/Water quality/Replication Package")

pop<-raster("Data/Population/Raw/Dasymetric_Population_CONUS_2010_V3.tif")

crs(pop)

summary(pop)
extent(pop)
extent(MARB)

#open MARB huc12
MARB<-st_read("Data/WatershedBoundaries/Processed/MARB/MARB.shp")

MARB<-st_transform(MARB, crs=st_crs(pop))

#make the same crs
crs(MARB)
crs(pop)

#crop raster to the extent of the MARB
#should make this go faster
pop<-raster::crop(pop, MARB)

#extract the data
pop_huc12<-exact_extract(pop, MARB, 'sum', progress=T)

pop_huc12<-as.data.frame(pop_huc12)
colnames(pop_huc12)<-"pop_est"

#merge to huc12 id
MARB<-subset(MARB, select="huc12")
MARB<-st_drop_geometry(MARB)

pop<-cbind(MARB, pop_huc12)

rm(MARB)
rm(pop_huc12)

pop_huc12<-pop

save(pop_huc12, file="Data/Population/Processed/pop_huc12.RData")

